// import QtQuick 1.0 // to target S60 5th Edition or Maemo 5
import QtQuick 1.1
import QMLFile 1.0
import "Android"
import "Components"
import "ControlPanel"
import "./js/ThemeInfo.js" as ThemeInfo
import "./js/Database.js" as Database

Rectangle {
    id:_root
    width: 800
    height: 640

    Component.onCompleted: {
        var path = Database.readData("THEMEPATH");
        path = (path === undefined) ? "" : path;
        var adbpath = Database.readData("ADBPATH");
        _androidDevice.adbPath = (adbpath === undefined) ? "" : adbpath;

        _themeSetting.rootPath = path;
        if(_themeSetting.rootPath.length > 0){
            //リスト更新
            _themeList.updateThemeList(_themeSetting.rootPath);
            _androidDevice.updateDeviceList();
            //内容更新
//            _themeSetting.update();
        }else{
            //ない
            var dir = _file.getExistingDirectory(qsTr("JcThemeSimulator : Please select your theme folder."), "");
            //変更
            changeThemePath(dir);
        }

        //ウインドウサイズ計算
        calcWidth();
    }
    Component.onDestruction: {
        Database.saveData("THEMEPATH", _themeSetting.rootPath);
        Database.saveData("ADBPATH", _androidDevice.adbPath);
    }

    //ウインドウの横幅を計算
    function calcWidth(){
        var temp = _android.width
                + _controlArea.width + _controlArea.anchors.leftMargin
                + _selectArea.width + _selectArea.anchors.leftMargin
                + _selectArea.anchors.leftMargin;
        if(_root.width < temp){
            _root.width = temp;
        }
    }

    // テーマフォルダの位置変更
    function changeThemePath(path){
        if(path.length < 1){
        }else{
            while(path.indexOf("\\") > 0){
                path = path.replace("\\", "/");
            }
            var pos = path.lastIndexOf("/");
            if(pos === path.length){
                path = path.substring(0, path.length - 1);
            }
            _themeSetting.rootPath = path;

            //リスト更新
            _themeList.updateThemeList(path);
            //内容更新
//            _themeSetting.update();
        }
    }


    Item{
        id: _themeSetting

        property string rootPath: ""                //テーマのルートパス（最後に/はいらない）
        property string themeName: ""               //選択してるテーマの名前（フォルダ名）
        property string pathBase: rootPath + "/" + themeName + "/"
        property string remotePathBase: "/sdcard/mytheme/" + themeName
        property string remotePathTemp: "/sdcard/mytheme/.JTS_TEMP"

        function update(){
            //launcher
            _android.launcherPath = [checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_LAUNCHER"]
                                                     , ThemeInfo.ITEM_DEFAULT_PATH["PATH_LAUNCHER"])
                                     , checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_LAUNCHER_LAND"]
                                                   , ThemeInfo.ITEM_DEFAULT_PATH["PATH_LAUNCHER"])];
            //lock screen
            _android.lockScreenPath = checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_LOCKSCREEN"]
                                                     , ThemeInfo.ITEM_DEFAULT_PATH["PATH_LOCKSCREEN"]);
            //navi key
            _android.naviKeyBackPath = [checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_NAVIKEY_BACK"]
                                                     , ThemeInfo.ITEM_DEFAULT_PATH["PATH_NAVIKEY_BACK"])
                                        , checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_NAVIKEY_BACK_LAND"]
                                                      , ThemeInfo.ITEM_DEFAULT_PATH["PATH_NAVIKEY_BACK_LAND"]) ];
            _android.naviKeyBackImePath = [checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_NAVIKEY_BACK_IME"]
                                                     , ThemeInfo.ITEM_DEFAULT_PATH["PATH_NAVIKEY_BACK_IME"])
                                        , checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_NAVIKEY_BACK_IME_LAND"]
                                                      , ThemeInfo.ITEM_DEFAULT_PATH["PATH_NAVIKEY_BACK_IME_LAND"]) ];
            _android.naviKeyExpandPath = [checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_NAVIKEY_EXPAND"]
                                                     , ThemeInfo.ITEM_DEFAULT_PATH["PATH_NAVIKEY_EXPAND"])
                                          , checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_NAVIKEY_EXPAND_LAND"]
                                                        , ThemeInfo.ITEM_DEFAULT_PATH["PATH_NAVIKEY_EXPAND_LAND"]) ];
            _android.naviKeyHomePath = [checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_NAVIKEY_HOME"]
                                                     , ThemeInfo.ITEM_DEFAULT_PATH["PATH_NAVIKEY_HOME"])
                                        , checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_NAVIKEY_HOME_LAND"]
                                                      , ThemeInfo.ITEM_DEFAULT_PATH["PATH_NAVIKEY_HOME_LAND"]) ];
            _android.naviKeyMenuPath = [ checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_NAVIKEY_MENU"]
                                                     , ThemeInfo.ITEM_DEFAULT_PATH["PATH_NAVIKEY_MENU"])
                                        , checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_NAVIKEY_MENU_LAND"]
                                                      , ThemeInfo.ITEM_DEFAULT_PATH["PATH_NAVIKEY_MENU_LAND"]) ];
            _android.naviKeyRecentPath = [ checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_NAVIKEY_RECENT"]
                                                     , ThemeInfo.ITEM_DEFAULT_PATH["PATH_NAVIKEY_RECENT"])
                                          , checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_NAVIKEY_RECENT_LAND"]
                                                        , ThemeInfo.ITEM_DEFAULT_PATH["PATH_NAVIKEY_RECENT_LAND"]) ];
            //notification
            _android.notificationItemNormalPath = [ checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_NOTIFICATION_ITEM_NORMAL"]
                                                     , ThemeInfo.ITEM_DEFAULT_PATH["PATH_NOTIFICATION_ITEM_NORMAL"])
                                                   , checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_NOTIFICATION_ITEM_LAND_NORMAL"]
                                                                 , ThemeInfo.ITEM_DEFAULT_PATH["PATH_NOTIFICATION_ITEM_LAND_NORMAL"])];
            _android.notificationItemPressedPath = [ checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_NOTIFICATION_ITEM_PRESSED"]
                                                     , ThemeInfo.ITEM_DEFAULT_PATH["PATH_NOTIFICATION_ITEM_PRESSED"])
                                                    , checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_NOTIFICATION_ITEM_LAND_PRESSED"]
                                                                  , ThemeInfo.ITEM_DEFAULT_PATH["PATH_NOTIFICATION_ITEM_LAND_PRESSED"])];
            _android.notificationTrackingBgPath = [ checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_NOTIFICATION_TRACKINGBG"]
                                                     , ThemeInfo.ITEM_DEFAULT_PATH["PATH_NOTIFICATION_TRACKINGBG"])
                                                   , checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_NOTIFICATION_TRACKINGBG_LAND"]
                                                                 , ThemeInfo.ITEM_DEFAULT_PATH["PATH_NOTIFICATION_TRACKINGBG_LAND"])];
            //screen shot
            _android.screenshotPath = [ checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_SCREENSHOT"]
                                                     , ThemeInfo.ITEM_DEFAULT_PATH["PATH_SCREENSHOT"])
                                       , checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_SCREENSHOT_LAND"]
                                                     , ThemeInfo.ITEM_DEFAULT_PATH["PATH_SCREENSHOT_LAND"]) ];
            //wallpaper
            _android.wallpaperPath = checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_WALLPAPER"]
                                                     , ThemeInfo.ITEM_DEFAULT_PATH["PATH_WALLPAPER"]);
            //recent frame
            _android.recentFramePath = checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_RECENT_FRAME"]
                                                     , ThemeInfo.ITEM_DEFAULT_PATH["PATH_RECENT_FRAME"]);
            //status bar
            _android.statusBarBackgroundPath = [ checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_STATUSBAR_BAR_BACKGROUND"]
                                                           , ThemeInfo.ITEM_DEFAULT_PATH["PATH_STATUSBAR_BAR_BACKGROUND"])
                                                , checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_STATUSBAR_BAR_BACKGROUND_LAND"]
                                                              , ThemeInfo.ITEM_DEFAULT_PATH["PATH_STATUSBAR_BAR_BACKGROUND_LAND"])];
            //simeji
            _android.imeSimejiPath = [ checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_SIMEJI_JCROM_PORT"]
                                                           , ThemeInfo.ITEM_DEFAULT_PATH["PATH_SIMEJI_JCROM_PORT"])
                                      , checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_SIMEJI_JCROM_LAND"]
                                                    , ThemeInfo.ITEM_DEFAULT_PATH["PATH_SIMEJI_JCROM_LAND"]) ];

            //navi bar
            _android.naviBarBackGroundPath = [ checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_NAVIBAR_BACKGROUND_PORT"]
                                                           , ThemeInfo.ITEM_DEFAULT_PATH["PATH_NAVIBAR_BACKGROUND_PORT"])
                                      , checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_NAVIBAR_BACKGROUND_LAND"]
                                                    , ThemeInfo.ITEM_DEFAULT_PATH["PATH_NAVIBAR_BACKGROUND_LAND"]) ];

            _android.phoneDialBackgroundPath = checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_PHONE_DIAL_BACKGROUND"]
                                                           , "");

            //wifi
            _android.statusBarWifiPath = checkExistsOneInList(pathBase
                                                             , ThemeInfo.ITEM_PATH["PATH_STATUSBAR_WIFI"]
                                                             , ThemeInfo.ITEM_DEFAULT_PATH["PATH_STATUSBAR_WIFI"]
                                                             , 5);
            _android.statusBarWifiFullyPath = checkExistsOneInList(pathBase
                                                             , ThemeInfo.ITEM_PATH["PATH_STATUSBAR_WIFI_FULLY"]
                                                             , ThemeInfo.ITEM_DEFAULT_PATH["PATH_STATUSBAR_WIFI_FULLY"]
                                                             , 5);
            _android.statusBarWifiInOutPath = checkExistsList(pathBase
                                                              , ThemeInfo.ITEM_PATH["PATH_STATUSBAR_WIFI_DIRECTION"]
                                                              , ThemeInfo.ITEM_DEFAULT_PATH["PATH_STATUSBAR_WIFI_DIRECTION"]);
            //battery
            _android.statusBarBatteryPath = checkExistsOneInList(pathBase
                                                                 , ThemeInfo.ITEM_PATH["PATH_STATUSBAR_BATTERY"]
                                                                 , ThemeInfo.ITEM_DEFAULT_PATH["PATH_STATUSBAR_BATTERY"]
                                                                 , 101);
            _android.statusBarBatteryChargePath = checkExistsOneInList(pathBase
                                                                 , ThemeInfo.ITEM_PATH["PATH_STATUSBAR_BATTERY_CHARGE"]
                                                                 , ThemeInfo.ITEM_DEFAULT_PATH["PATH_STATUSBAR_BATTERY_CHARGE"]
                                                                 , 101);

            _androidBootAnimeLoader.animeDir = checkExists(pathBase + ThemeInfo.ITEM_PATH["PATH_BOOTANIME"], "");

            console.debug("SBAR=" + _android.statusBarBackgroundPath[0] + ", " + _android.statusBarBackgroundPath[1]);
        }

        function updateJcbeam(list){
            var path;
            var path_list = [];
            for(var i=0; i<list.length; i++){
                path = rootPath + "/" + list[i] + "/";
                path_list.push({"name": list[i]
                                   , "path": checkExists(path + ThemeInfo.ITEM_PATH["PATH_LAUNCHER"]
                                          , ThemeInfo.ITEM_DEFAULT_PATH["PATH_LAUNCHER"])
                               });
            }
            if(path_list.length > 0){
                _android.jcbeamThemeList = path_list;
            }
        }

        function reload(){
            //launcher
            _android.launcherPath = "";
            //lock screen
            _android.lockScreenPath = "";
            //navi key
            _android.naviKeyBackPath = ["", ""];
            _android.naviKeyExpandPath = ["", ""];
            _android.naviKeyHomePath = ["", ""];
            _android.naviKeyMenuPath = ["", ""];
            _android.naviKeyRecentPath = ["", ""];
            //notification
            _android.notificationItemNormalPath = ["", ""];
            _android.notificationItemPressedPath = ["", ""];
            _android.notificationTrackingBgPath = ["", ""];
            //screen shot
            _android.screenshotPath = ["", ""];
            //wallpaper
            _android.wallpaperPath = "";
            //recent frame
            _android.recentFramePath = "";
            //status bar
            _android.statusBarBackgroundPath = ["", ""];
            //simeji
            _android.imeSimejiPath = ["", ""];
            //navi bar
            _android.naviBarBackGroundPath = ["", ""];

            _android.phoneDialBackgroundPath = "";

            update();
        }

        //基準パスから存在をチェックする
        function checkExistsOneInList(base_path, path, default_paths, count){
            var ret = [];
            var temp;
            for(var i=0;i<count;i++){
                temp = base_path + path.replace("%d",i);
                if(_file.exists(temp)){
                    ret.push(temp);
                }
            }
            if(ret.length > 0){
                return ret;
            }else{
                return default_paths;
            }
        }

        //存在チェックをリストで実施
        function checkExistsList(base_path, paths, default_paths){
            var ret = [];
            for(var i=0; i<paths.length; i++){
                if(_file.exists(base_path + paths[i])){
                    ret.push(base_path + paths[i]);
                }else{
                    ret.push(default_paths[i]);
                }
            }
            return ret;
        }

        // 存在チェック
        function checkExists(path, default_path){
            if(_file.exists(path)){
                return path;
            }else{
                return default_path;
            }
        }
    }

    QMLFile{
        id: _file
        operationState: QMLFile.Idle
        onOperationStateChanged:{

//            console.debug("s change:" + operationState + "," + QMLFile.Idle);
        }
    }

    // 背景
    Image{
        anchors.fill: parent
        source: "images/background.png"
        fillMode: Image.Tile
    }

    //アンドロイド
    AndroidDesktop{
        id: _android
        clip: true
        isPortrait: true
    }

    //操作パネルと
    Row{
        id: _controlArea
        anchors.top: parent.top
        anchors.left: _android.right
        anchors.topMargin: 10
        anchors.leftMargin: _android.isPortrait ? 10 : -130
        spacing: 5

        //操作パネル
        ControlPanel{
            enabledBootButton: _androidBootAnimeLoader.exist
            enabledRebootButton: _androidBootAnimeLoader.exist & _android.bootAnimeLoaded
            isPortrait: _android.isPortrait

            onScreenLock: {
                _android.screenLock(is);
            }
            onTakeScreenShot: {
                _android.takeScreenShot();
            }
            onBoot: {
                _androidBootAnimeLoader.visible = true;
            }
            onReboot: {
                _android.boot(_androidBootAnimeLoader.getPaths());
            }
            onRotated: {
                _android.isPortrait = r;
            }
            onWifiSignalChanged: {
                _android.wifiSignal = num;
            }
            onIsWifiSignalFullyChanged: {
                _android.isWifiSignalFully = is;
            }
            onWifiDirectionChanged: {
                _android.wifiDirection = num;
            }
            onBatteryChargeChanged: {
                _android.batteryCharge = num;
            }
            onIsBatteryChargeChanged: {
                _android.isBatteryCharge = is;
            }
            onNumberOfHomeScreen: {
                _android.numberOfHomescreen = num;
            }
        }
    }

    //テーマとデバイス
    Column{
        id: _selectArea
        anchors.top: parent.top
        anchors.left: _controlArea.right
        anchors.topMargin: 10
        anchors.leftMargin: 10
        spacing: 5

        //テーマ一覧
        ThemeList{
            id: _themeList
            onThemeNameChanged: {
                //テーマ選択更新
                _android.boot(undefined);
                _themeSetting.themeName = themeName;
                _themeSetting.update();
            }
            onThemeListChanged: {
                //テーマの一覧更新
                _themeSetting.updateJcbeam(themeList);
            }
            onReloadTheme: {
                _themeSetting.reload();
            }
        }

        //デバイス操作
        AndroidDevice{
            id: _androidDevice
            localPath: _themeSetting.pathBase
            remotePath: _themeSetting.remotePathBase
            remotePathTemp: _themeSetting.remotePathTemp

            onStartProgress: {
                _progress.progressMax = max;
                _progress.progressValue = 0;
                _progress.visible = true;
            }
            onUpdateProgress: {
                _progress.progressValue = value;
                _progress.progressMessage = message;
            }
            onEndProgress: {
                _progress.progressValue = _progress.progressMax;
                _progress.visible = false;

                _toast.show(qsTr("Finished"));
            }

            onShowDialog: {
                _messageDlg.dialogTitle = title;
                _messageDlg.dialogMessage = message;
                _messageDlg.callbackElm = myelm;
                _messageDlg.callbackId = id;
                _messageDlg.visible = true;
            }
        }
    }

    //起動アニメの設定ダイアログ
    AndroidBootAnimeLoader{
        id: _androidBootAnimeLoader
        visible: false

        onOkClicked: {
            _android.boot(getPaths());
        }
    }

    //プログレス
    DialogProgress{
        id: _progress
        anchors.fill: parent
    }

    //メッセージ
    DialogMessage{
        id: _messageDlg
        anchors.fill: parent
        visible: false

        property variant callbackElm: null
        property int callbackId: 0

        onClickOkButton: {
            callbackElm.callbackMessageDialog(callbackId);
            visible = false;
        }
        onClickCancelButton: {
            visible = false;
        }
    }

    //トースト
    Toast{
        id: _toast
        anchors.centerIn: parent
        pixelSize: 18
    }

//    Image{
//        id: _debugImage
//        anchors.top: parent.top
//        anchors.left: parent.left
////        anchors.left: _android.right
//        width: _android.width
//        height: _android.height
////        width: _android.height
////        height: _android.width
//        source: "test/sample_home4.png"
//        opacity: 0.5
//        visible: true
//    }

    Text{
        id: _credit
        anchors.right: parent.right
        anchors.bottom: parent.bottom
        anchors.rightMargin: 5
        text: "JcThemeSimulator ver 0.9" //"  (C) 2012 IoriAYANE"
        color: "#dddddd"

//        MouseArea{
//            anchors.fill: parent
//            onClicked: {
//                if(_debugImage.opacity > 0){
//                    _debugImage.opacity = 0;
//                }else{
//                    _debugImage.opacity = 0.5;
//                }
//            }
//        }
    }
}
